import { useDeepCompareEffect, useDynamicList } from 'ahooks';
import { Button, Col, Empty, Form, Icon, Select, Tooltip } from 'antd';
import classNames from 'classnames';
import React, { forwardRef, useContext, useImperativeHandle } from 'react';
import ConditionGroup from '@/components/ConditionGroup';
import styles from '../styles.less';
import ValidatorContext from '../ValidatorContext';
import BasicForString from './BasicForString';

function AdvancedForString({ node, value = [], onChange, filter }, ref) {
  const { list, remove, getKey, push, replace } = useDynamicList(value);
  const { state } = useContext(ValidatorContext);

  const addRule = () => push({});

  useImperativeHandle(ref, () => ({
    addRule,
  }));

  useDeepCompareEffect(() => {
    onChange(list);
  }, [list]);

  const Row = (index, item) => (
    <div key={getKey(index)} className={styles.block}>
      <div className={styles.counter}>
        <span className={styles.num}>{index}</span>
        <span className={classNames(styles.delete, 'text-danger')} onClick={() => remove(index)}>
          <Tooltip title="删除">
            <Icon type="close" />
          </Tooltip>
        </span>
      </div>
      <Form.Item label="条件">
        <ConditionGroup
          treeData={[state.rootNode]}
          value={item.condition}
          onChange={value => replace(index, { ...item, condition: value })}
        />
      </Form.Item>
      <Form.Item label="规则">
        <div className="margin-top">
          <BasicForString
            node={node}
            filter={filter}
            value={item.config}
            onChange={config => replace(index, { ...item, config })}
          />
        </div>
      </Form.Item>
    </div>
  );

  if (list.length === 0) {
    return (
      <Empty>
        <Button icon="plus" type="link" style={{ padding: 0 }} onClick={addRule}>
          添加一组规则
        </Button>
      </Empty>
    );
  }

  return list.map((ele, index) => Row(index, ele));
}

export default forwardRef(AdvancedForString);
